package com.kb.service.impl.crm;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.common.MeException;
import com.kb.domain.WaitingInvoice;
import com.kb.dto.InvoiceDetailsDTO;
import com.kb.dto.InvoiceSearchDTO;
import com.kb.dto.WaitingInvoiceDTO;
import com.kb.dto.crm.YLCrmInfo;
import com.kb.entity.crm.*;
import com.kb.entity.kbidm.CustomerRequest;
import com.kb.mapper.sqlServer.CrmInvoiceMapper;
import com.kb.mapper.sqlServer.crm.CrmParameterGroupItemMapper;
import com.kb.mapper.sqlServer.crm.CrmParameterValuesMapper;
import com.kb.mapper.sqlServer.crm.UserInfoMapper;
import com.kb.mapper.sqlServer.kbidm.*;
import com.kb.service.crm.KBEService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@DS("SmartQuote_kb_live")
@Service
@Slf4j
public class KBEServiceImpl implements KBEService {
    @Resource
    private CrmInvoiceMapper invoiceMapper;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private CrmShipmentMapper shipmentMapper;
    @Resource
    private CrmCollateStatementItemMapper collateStatementItemMapper;
    @Resource
    private CrmCollateStatementMapper collateStatementMapper;
    @Resource
    private CRMCustomerMapper customerMapper;
    @Resource
    private InvoiceItemMapper invoiceItemMapper;
    @Resource
    private KbContactsMapper contactsMapper;
    @Resource
    private NumberControlMapper numberControlMapper;
    @Resource
    private CustomerAddressMapper  customerAddressMapper;
    @Resource
    private CrmParameterValuesMapper  parameterValuesMapper;
    @Resource
    private CrmParameterGroupItemMapper parameterGroupItemMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Override
    public Page<Invoice> queryInvoice(InvoiceSearchDTO invoiceSearchDTO) {
        log.info("查询开票信息：{}", JSONUtil.toJsonStr(invoiceSearchDTO));
        if (Objects.nonNull(invoiceSearchDTO.getRule()) && invoiceSearchDTO.getRule()){
            invoiceSearchDTO.setCustCode(null);
        }
        Page<Invoice> page = new Page<>(invoiceSearchDTO.getPage(), invoiceSearchDTO.getRows());

        return invoiceMapper.queryInvoice(page,invoiceSearchDTO);
    }

    @Override
    public Invoice queryInvoiceById(String id) {
        return invoiceMapper.selectById(id);
    }

    @Override
    public List<InvoiceDetailsDTO> queryInvoiceDetails(String id) {
        //i.subAmount / ( 1+ i.taxRate ) 未含税的金额
        // i.subAmount / ( 1+ i.taxRate ) * i.taxRate  税额
        List<InvoiceDetailsDTO> invoiceDetailsDTOList = invoiceMapper.queryInvoiceDetails(id);
        if (CollectionUtil.isNotEmpty(invoiceDetailsDTOList)){
            invoiceDetailsDTOList.forEach(e ->{
                if (Objects.nonNull(e.getTaxAmount())){
                    //保留4位小数
                    e.setTaxAmount(e.getTaxAmount().setScale(4, RoundingMode.HALF_UP));
                }
            });
            return invoiceDetailsDTOList;
        }
        return new ArrayList<>();
    }

    @Override
    public Page<WaitingInvoice> queryWaitingInvoice(InvoiceSearchDTO invoiceSearchDTO) {
        log.info("查询待开票信息：{}", JSONUtil.toJsonStr(invoiceSearchDTO));
        Page<Invoice> page = new Page<>(invoiceSearchDTO.getPage(), invoiceSearchDTO.getRows());
        // todo 额外费用返回到页面，后续开票的时候，带回，进行对账开票，= 各种费用之和（光绘，工程，测试，拼版，加急，其他）
        Page<WaitingInvoiceDTO> waitingInvoiceDTOPage = invoiceMapper.queryWaitingInvoice(page, invoiceSearchDTO);
        List<WaitingInvoiceDTO> records = waitingInvoiceDTOPage.getRecords();
        List<WaitingInvoice> record = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)){
            waitingInvoiceDTOPage.getRecords().forEach(e ->{
                WaitingInvoice waitingInvoice = new WaitingInvoice();
                BeanUtil.copyProperties(e,waitingInvoice);
                waitingInvoice.setAddFeeing(e.getEngFee().add(e.getFilmFee()).add(e.getToolFee()).add(e.getPnlFee()).add(e.getRushFee()).add(e.getOtherFee().subtract(e.getAddFeeing())));
                record.add(waitingInvoice);
            });
        }
        Page<WaitingInvoice> resultPage = new Page<>();
        BeanUtil.copyProperties(waitingInvoiceDTOPage,resultPage);
        resultPage.setRecords(record);
        return resultPage;
    }

    @Override
    @DSTransactional
    public void applyInvoicing(List<CrmShipment> shipments) {
        //TODO 先对账 然后 申请开票
        /**
         * arAmount = 制版费之和   nowAmount 制版费  测试客代 17018
         * 1.根据传入的数据，修改CRM_Shipment的数据
         * 2.根据参数，往CRM_CollateStatement表和CRM_CollateStatementItem插入数据，生成对账信息
         * 3.根据参数，往CRM_Invoice和CRM_InvoiceItem插入数据，生成开票信息
         */

        log.info("方法：applyInvoicing， 参数： {}", JSONUtil.parse(shipments));
        //把shipments里面的recId用,号拼接
//        List<Integer> recIds = shipments.stream().map(CrmShipment::getRecId).collect(Collectors.toList());
//        List<CrmShipment> shipmentList = shipmentMapper.selectBatchIds(recIds);
        BigDecimal arAmount = BigDecimal.ZERO;
        BigDecimal addTotalAmount = BigDecimal.ZERO;
        BigDecimal subAmount = BigDecimal.ZERO;  //制版费 = 单价 + 数量   目前页面只能调整数量  如果可以调整制版费 以页面传参为准
        if (CollectionUtils.isNotEmpty(shipments)){
            for (CrmShipment shipment : shipments) {
                subAmount =subAmount.add(shipment.getUnitPrice().multiply(BigDecimal.valueOf(shipment.getQtyCollated())));
                //剩余装运数量计算  剩余待对 - 页面填写的数量
                shipment.setQtyTobeConfirmed(shipment.getQtyTobeConfirmed() - shipment.getQtyCollated());
                //本次对账金额 : 已对账金额,已开票金额 = 制版费+ 额外费
//                BigDecimal addTotal = shipment.getNowAmount().add(shipment.getAddFeeing());
                shipment.setSubAmonting(subAmount);
                //todo  amountCollated，额外费用=各种费用相加 = 总金额 - 制版费		 subAmonting，置制版费=单价*数量 申请开票的时候 带给前端，
                //当分批次的时候 需要先查询已经对账开票的数据，然后和本次金额相加
                CrmShipment crmShipment = shipmentMapper.selectById(shipment.getRecId());
                BigDecimal addTotal = shipment.getNowAmount();
                shipment.setAmountCollated(addTotal.add(crmShipment.getAmountCollated()));
                shipment.setAmountInvoiced(addTotal.add(crmShipment.getAmountInvoiced()));
                //已对账 已开票数量
                shipment.setQtyCollated(shipment.getQtyCollated() + crmShipment.getQtyCollated());
                shipment.setQtyInvoiced(shipment.getQtyCollated() + crmShipment.getQtyCollated());
                shipmentMapper.updateById(shipment);
                arAmount = arAmount.add(shipment.getNowAmount());
//                addTotalAmount = addTotalAmount.add(shipment.getAddFeeing());
            }


        }
        //组装对账单表数据
        CrmCollateStatement crmCollateStatement = new CrmCollateStatement();
        String custCode = shipments.get(0).getCustCode();
        BigDecimal taxRate = shipments.get(0).getTaxRate();
        //总金额
        BigDecimal totalAmount = arAmount.add(addTotalAmount);
//        String dailySequence = generateDailySequence();
        crmCollateStatement.setCreatedBy("订单中台操作").setType("IN").setInvoiceFlg(false).setCustCode(custCode).setNote("订单中台自动对账");
        crmCollateStatement.setStatus("Confirmed").setCollateDate(new Date()).setSubmitDate(new Date());
        //未含税金额   税金 = 总金额减去未含税金额
        BigDecimal multiply = arAmount.divide(taxRate.add(BigDecimal.ONE), 4, RoundingMode.HALF_UP);
        crmCollateStatement.setNetAmount(multiply).setTaxAmount(arAmount.subtract(multiply));
        crmCollateStatement.setArAmount(totalAmount)
                .setSubAmount(subAmount).setTotalAmount(totalAmount).setAddCharge(addTotalAmount).setCreditAmount(BigDecimal.ZERO);
        //封装客户信息 查询税率，计算税额
        LinkManOfCustomer manOfCustomer = invoiceMapper.queryCustomerByCode(custCode);
        crmCollateStatement.setCustomerId(manOfCustomer.getCustomerId()).setContactName(manOfCustomer.getLinkManName()).setContactEmail(manOfCustomer.getEmail()).setCreateDate(new Date());

        collateStatementMapper.insert(crmCollateStatement);

        //发票主表插入数据  setSubAmount=制版费
        Invoice invoice = new Invoice();
        invoice.setType("IN").setInvoiceDate(new Date()).setStatus("Confirmed").setSubAmount(arAmount).setInvoiceType("AddVal").setDueDate(new Date()).setInvoiceBy("订单中台操作").setAddWay("Merge").setSubmitDate(new Date())
                .setTotalAmount(totalAmount).setTaxAmount(totalAmount).setCustomerId(manOfCustomer.getCustomerId()).setAddCharge(addTotalAmount).setArAmount(totalAmount);
        invoice.setNetAmount(multiply).setTaxAmount(arAmount.subtract(multiply)).setCustCode(custCode);
        invoice.setCurrencyId(1).setAmountPaid(BigDecimal.ZERO).setCreditAmount(BigDecimal.ZERO);
        invoice.setCustomerId(manOfCustomer.getCustomerId()).setContactName(manOfCustomer.getLinkManName()).setContactEmail(manOfCustomer.getEmail());
        invoiceMapper.insert(invoice);

        for (CrmShipment shipment : shipments) {
            //对账明细
            CrmCollateStatementItem crmCollateStatementItem = new CrmCollateStatementItem();
//            BigDecimal addTotal = shipment.getNowAmount().add(shipment.getAddFeeing());
            BigDecimal addTotal = shipment.getNowAmount();

            crmCollateStatementItem.setShipmentId(shipment.getRecId()).setQtyInvoiceTobeConfirmed(shipment.getQtyTobeConfirmed()).setCollateStatementId(crmCollateStatement.getRecId())
                    .setUnitPrice(shipment.getUnitPrice())
//                    .setTotalAmount(shipment.getNowAmount().add(shipment.getAddFeeing()))
                    .setTotalAmount(shipment.getNowAmount())
                    .setSubAmonting(BigDecimal.ZERO).setSubAmount(shipment.getNowAmount())
                    //未开票设置  开票这两个字段为0
//                    .setAmountInvoiceTobeConfirmed(shipment.getNowAmount()).setQtyInvoiceTobeConfirmed(shipment.getQtyCollated())
                    .setAmountInvoiceTobeConfirmed(BigDecimal.ZERO).setQtyInvoiceTobeConfirmed(0)
                    .setAddFeeing(BigDecimal.ZERO) //这个字段是工程费用  kbe那边只有额外费用 就是各个费用之和
                    .setSubAmount(shipment.getUnitPrice().multiply(BigDecimal.valueOf(shipment.getQtyCollated())))//制版费
                    .setAddCharge(shipment.getAddFeeing()).setChargeConfirmed(true).setAmountPaid(addTotal).setInvoiceChargeConfirmed(false)
                    .setQtyConfirmed(shipment.getQtyCollated()).setTaxRate(shipment.getTaxRate());
            collateStatementItemMapper.insert(crmCollateStatementItem);
            //发票明细
            InvoiceItem invoiceItem = new InvoiceItem();
            invoiceItem.setShipmentId(shipment.getRecId()).setInvoiceId(invoice.getRecId()).setCollateStatementId(crmCollateStatement.getRecId()).setCollateStatementItemId(crmCollateStatementItem.getRecId())
                    .setUnitPrice(shipment.getUnitPrice())
//                    .setTotalAmount(shipment.getNowAmount().add(shipment.getAddFeeing()))
                    .setTotalAmount(shipment.getNowAmount())
                    .setSubAmonting(BigDecimal.ZERO)
                    .setSubAmount(subAmount)//制版费
                    .setAmountCashTobeConfirmed(addTotal)//本次开票金额
                    .setAddFeeing(BigDecimal.ZERO) //这个字段是工程费用  kbe那边只有额外费用 就是各个费用之和
                    .setAddCharge(shipment.getAddFeeing())
                    .setChargeConfirmed(true).setAmountPaid(BigDecimal.ZERO).setQtyCashTobeConfirmed(shipment.getQtyCollated()).setCashChargeConfirmed(false)
                    .setQtyConfirmed(shipment.getQtyCollated()).setQtyConfirmed(shipment.getQtyCollated()).setTaxRate(shipment.getTaxRate());

            invoiceItemMapper.insert(invoiceItem);
        }

    }

    @Override
    public List<YLCrmInfo> getCrmCustomer(YLCrmInfo ylCrmInfo) {
        List<YLCrmInfo> list = new ArrayList<>();
        if (Objects.nonNull(ylCrmInfo.getPhone()) || Objects.nonNull(ylCrmInfo.getEmail()) ||Objects.nonNull(ylCrmInfo.getUserName()) || Objects.nonNull(ylCrmInfo.getCustomerName())) {
            List<Customer> crmList = new ArrayList<>();
            //查询客户数据
            LambdaQueryWrapper<Customer> lambda = new QueryWrapper<Customer>().lambda();
            if (Objects.nonNull(ylCrmInfo.getPhone())) {
                lambda.or().like(Customer::getCusttel, ylCrmInfo.getPhone());
            }
            if (Objects.nonNull(ylCrmInfo.getEmail())) {
                lambda.or().like(Customer::getCustemail, ylCrmInfo.getEmail());
            }
            if (Objects.nonNull(ylCrmInfo.getCustomerName())) {
                lambda.or().like(Customer::getCustname, ylCrmInfo.getCustomerName());
            }
            if (Objects.isNull(ylCrmInfo.getPhone()) && Objects.isNull(ylCrmInfo.getEmail()) && Objects.isNull(ylCrmInfo.getCustomerName())) {
                crmList = null;
            }else {
                crmList = customerMapper.selectList(lambda);
            }
            //查询联系人
            List<Customer> manOfCustomerList = contactsMapper.getCrmCustomer(ylCrmInfo);
            if (CollectionUtils.isNotEmpty(crmList)){
                manOfCustomerList.addAll(crmList);
            }
            if (CollectionUtils.isNotEmpty(manOfCustomerList)){
                for (Customer manOfCustomer : manOfCustomerList) {
                    YLCrmInfo crmInfo = new YLCrmInfo();
                    crmInfo.setCustomerName(manOfCustomer.getCustname());
                    list.add(crmInfo);
                }
            }
        }
        return list;
    }

    @Override
    @DSTransactional
    public boolean createCustomer(CustomerRequest customerRequest) {
        log.info("方法：createCustomer， 参数： {}", JSONUtil.parse(customerRequest));
        //获取最新客户代码
        NumberControl control = numberControlMapper.selectOne();
        int custCode = control.getSerialNumber();
        Customer customer = new Customer();
        //默认数据赋值
        if (Objects.isNull(customerRequest.getRkey())){
            throw new MeException("Rkey不能为空");
        }
        customer.setSysuserid(Integer.valueOf(customerRequest.getRkey()));
        customer.setCustcode(String.valueOf(custCode)).setDepartmentid(1420).setStatus("Valid").setType("EnterpriseCustomer").setApprovestatus("Approved").setAreaid(1)
                .setIfreconce(1).setIfactive(1).setCountryid(1d).setCountryid(1d).setTaxid(2).setPaymenttermid(19).setSaletype("ForDomestic").setSource("Network").setRegtime(new Date())
                .setDifferent("IN-IN").setEntatt("InternalOther").setCustatt("Development").setSource("Network");
        //基本信息
        CustomerRequest.MainInformation mainInformation = customerRequest.getMainInformation();
        CustomerRequest.Account account = customerRequest.getAccount();
        customer.setCustname(mainInformation.getCompanyName())
                .setCustnickname(mainInformation.getCustNickName())
                .setCustaddress(mainInformation.getCompanyRegisteredAddress())
                .setCusttel(account.getTelNumber())
                .setCustemail(account.getEmail())
                .setCustcode(customerRequest.getUserInputCode());
        //发票信息
        CustomerRequest.InvoiceInfo invoiceInfo = customerRequest.getInvoiceInfo();
        customer.setBillingcompany(invoiceInfo.getInvoice_Header())
                .setTariff(invoiceInfo.getTaxpayer_Number())
                .setRegno(invoiceInfo.getTaxpayer_Number())
                .setBank(invoiceInfo.getDeposit_Bank())
                .setAccount(invoiceInfo.getBank_Account())
//                .setBillingadd(invoiceInfo.getMailingAddress() +"   "+  invoiceInfo.getContact_Tel())
                .setCustemail(customerRequest.getAccount().getEmail())
                .setCustwebsite(invoiceInfo.getF_Description());
        if (StringUtils.isNotBlank(invoiceInfo.getMailingAddress()) || StringUtils.isNotBlank(invoiceInfo.getContact_Tel())){
            customer.setBillingadd(invoiceInfo.getMailingAddress() +"   "+  invoiceInfo.getContact_Tel());
        }

        customerMapper.insert(customer);
        //客户 参数信息
        List<CrmParameterGroupItem> crmParameterGroupItems = parameterGroupItemMapper.selectList(Wrappers.lambdaQuery(CrmParameterGroupItem.class).eq(CrmParameterGroupItem::getParameterGroupId, 14));;
        for (CrmParameterGroupItem parameterGroupItem : crmParameterGroupItems) {
            CrmParameterValues crmParameterValues = new CrmParameterValues();
            crmParameterValues.setSourceType("Customer");
            crmParameterValues.setSourceId(customer.getRecid());
            Map<String, String> stringStringMap = this.parseParameterGroupItem(parameterGroupItem.getSetValue());
            if (parameterGroupItem.getParamName().equals("所属行业")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setParameterValue(mainInformation.getCustNickName());
                crmParameterValues.setTextValue(stringStringMap.get("计算机及周边"));
                crmParameterValues.setParameterValue("计算机及周边");
                parameterValuesMapper.insert(crmParameterValues);
            }
            if (parameterGroupItem.getParamName().equals("合作业务")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setTextValue(stringStringMap.get("PCB"));
                crmParameterValues.setParameterValue("PCB");
                parameterValuesMapper.insert(crmParameterValues);
            }
            if (parameterGroupItem.getParamName().equals("企业信用")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setTextValue(stringStringMap.get("无违法失信记录，经营正常"));
                crmParameterValues.setParameterValue("无违法失信记录，经营正常");
                parameterValuesMapper.insert(crmParameterValues);
            }
            if (parameterGroupItem.getParamName().equals("环保要求")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setTextValue(stringStringMap.get("RoHS"));
                crmParameterValues.setParameterValue("RoHS");
                parameterValuesMapper.insert(crmParameterValues);
            }
            if (parameterGroupItem.getParamName().equals("签约主体")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setTextValue(stringStringMap.get("惠州"));
                crmParameterValues.setParameterValue("惠州");
                parameterValuesMapper.insert(crmParameterValues);
            }
            if (parameterGroupItem.getParamName().equals("渠道来源")){
                crmParameterValues.setParameterGroupItemId(parameterGroupItem.getRecId());
                crmParameterValues.setTextValue(stringStringMap.get("惠州"));
                crmParameterValues.setParameterValue("惠州");
                parameterValuesMapper.insert(crmParameterValues);
            }
        }

        //客户代码+1 更新客户代码
        control.setSerialNumber(custCode + 1);
        numberControlMapper.updateById(control);

        //联系人信息
        LinkManOfCustomer contacts = new LinkManOfCustomer();
        contacts.setCustomerId(String.valueOf(customer.getRecid()))
                .setLinkManName(mainInformation.getCustNickName())
                .setMobile(account.getTelNumber())
                .setEmail(customerRequest.getAccount().getEmail());
                contactsMapper.insert(contacts);
        //地址信息
        CustomerAddress customerAddress = new CustomerAddress();
        customerAddress.setCustomerid(String.valueOf(customer.getRecid()))
                .setAddress(invoiceInfo.getMailingAddress())
                .setConsignee(mainInformation.getCustNickName())
                .setName(mainInformation.getCustNickName())
                .setTel(account.getTelNumber())
                .setSort(1);
        customerAddressMapper.insert(customerAddress);
        return true;
    }
    public Map<String, String> parseParameterGroupItem(String setValue) {
        Map<String, String> resultMap = new HashMap<>();
        if (setValue == null || setValue.isEmpty()) {
            return resultMap;
        }

        // 按分号分割各个条目
        String[] entries = setValue.split(";");
        for (String entry : entries) {
            // 按冒号分割每个条目的键和值
            String[] parts = entry.split(":");
            if (parts.length == 2) {
                String key = parts[1];   // 类别名称
                String value = parts[0]; // 编号
                resultMap.put(key, value);
            }
        }

        return resultMap;
    }
    @Override
    public int getCustomCode() {
        //获取最新客户代码
        NumberControl control = numberControlMapper.selectOne();
        int custCode = control.getSerialNumber();
        //客户代码+1 更新客户代码
        control.setSerialNumber(custCode + 1);
        numberControlMapper.updateById(control);
        return custCode;
    }

    @Override
    public List<UserInfo> getSales() {
        LambdaQueryWrapper<UserInfo> userInfo = Wrappers.lambdaQuery();
        userInfo.eq(UserInfo::getUserGroup, "Sales");
        return userInfoMapper.selectList(userInfo);
    }

    @Override
    public String generateDailySequence() {
        String prefix = "DD-DZD";
        String formattedSequence = "";
        try (Connection connection = jdbcTemplate.getDataSource().getConnection();
             CallableStatement callableStatement = connection.prepareCall("{call GetNextDailySequence(?)}")) {

            // 注册输出参数
            callableStatement.registerOutParameter(1, Types.NVARCHAR);

            // 执行存储过程
            callableStatement.execute();

            // 获取当前日期并格式化为 yyyyMMdd
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String currentDate = dateFormat.format(new Date());
            Integer todaySequence = invoiceMapper.getTodaySequence(currentDate);

            // 格式化序列号为5位数字，不足5位前面补0
            String formattedCurrentSequence = String.format("%05d", todaySequence);
            // 组合成最终的序列号字符串
            formattedSequence = String.format("%s-%s-%s", prefix, currentDate, formattedCurrentSequence);

        } catch (SQLException e) {
            log.error("Error 获取流水号失败: ", e);
        }
        return formattedSequence;
    }

}
